<template>
  <VTable ref="tableRef" v-bind="tableOptins">
    <template #form="{ form }">
      <el-input
        v-model="form.filterText"
        style="width: 300px"
        placeholder="商品名称"
        clearable
        prefix-icon="Search"
      ></el-input>
    </template>
    <template #toolbar_btns>
      <el-button
        @click="batchOptionsRole"
        v-hasPermi="[userSysAuthList.attribute.manage_product_categories_roles]"
        >批量分配角色</el-button
      >
      <el-button
        @click="batchOptionsUser"
        v-hasPermi="[userSysAuthList.attribute.manage_product_category_people]"
        >批量分配人员</el-button
      >
    </template>
  </VTable>
  <VRoleManage
    v-model="roleVisible"
    :data="roleData"
    :api="roleApi"
    @close="roleData = {}"
    @refresh="refresh"
  ></VRoleManage>
  <VUserManage
    v-model="userVisible"
    :data="userData"
    :api="userApi"
    @close="userData = {}"
    @refresh="refresh"
  ></VUserManage>
</template>
<script setup lang="jsx">
import { ElMessage } from "element-plus";
import { treeToArray } from "../../data.js";
import api from "../../api/index.js";
import VRoleManage from "@/components/VRoleManage";
import VUserManage from "@/components/VUserManage";
import { userSysAuthList } from "@/Auth/userSys.js";
import { isPermission } from "@/hooks/permission.js";
const props = defineProps({
  optionsData: { type: Object, default: () => {} },
});
const { optionsData } = toRefs(props);
const tableRef = ref();
const tableOptins = reactive({
  treeConfig: { transform: true, rowField: "id", parentField: "p_id" },
  formConfig: {
    data: {},
  },
  columns: [
    { type: "checkbox", width: "40" },
    {
      field: "name",
      title: "分类名称",
      treeNode: "tree-node",
      minWidth: "200",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <el-link type="primary" underline={false}>
                {row.name}
              </el-link>
            </div>
          );
        },
      },
    },
    {
      field: "status",
      title: "状态",
      width: "90",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              {row.status === 1 ? (
                <svg-icon
                  icon-class="enable"
                  class="mr-[2px] text-[14px] text-[var(--main-color)] inline"
                />
              ) : (
                <svg-icon
                  icon-class="disabled"
                  class="mr-[2px] text-[14px] text-[var(--info-color)] inline"
                />
              )}
              {row.status == 1 ? "启用" : "禁用"}
            </div>
          );
        },
      },
    },
    { field: "create_time", title: "添加时间", width: "200" },
    { field: "create_user", title: "添加人", width: "200" },
    {
      title: "操作",
      fixed: "right",
      width: "160",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              {isPermission([
                userSysAuthList.attribute.manage_product_categories_roles,
              ]) && (
                <el-button
                  type="primary"
                  onClick={() => {
                    handleRoleManage(row);
                  }}
                  link
                >
                  分配角色
                </el-button>
              )}
              {isPermission([
                userSysAuthList.attribute.manage_product_category_people,
              ]) && (
                <el-button
                  type="primary"
                  onClick={() => {
                    handleUesrManage(row);
                  }}
                  link
                >
                  分配人员
                </el-button>
              )}
            </div>
          );
        },
      },
    },
  ],
  proxyConfig: {
    ajax: {
      query: async ({ page, form }) => {
        return api.goodsCategory({ ...form }).then((res) => {
          let data = treeToArray(res.data);
          let filteredData = [];
          if (!form?.filterText) {
            filteredData = data;
          } else {
            filteredData = filterData(data, form.filterText);
          }
          console.log(filteredData);
          return {
            data: filteredData,
            total: filteredData.length,
          };
        });
      },
    },
  },
});
const roleData = ref({});
const roleVisible = ref(false);
const roleApi = ref("");
const batchOptionsRole = () => {
  let records = tableRef.value?.$table.getCheckboxRecords();
  if (!records?.length) return ElMessage.warning("请至少选择一条数据!");
  const ids = records.map((item) => item.id);
  roleData.value = {
    roletitle: "",
    roleType: "分类",
    roleData: [],
    parmas: { goods_category_ids: ids },
  };
  roleApi.value = api.setgoodsBatchAccessRole;
  roleVisible.value = true;
};
const handleRoleManage = async (val) => {
  const { data } = await api.accessRole({ goods_category_id: val.id });
  roleData.value = {
    roletitle: val.name,
    roleType: "分类",
    roleData: data?.role_ids || [],
    parmas: { goods_category_id: val.id },
  };
  roleApi.value = api.setAccessRole;
  roleVisible.value = true;
};
const userData = ref({});
const userVisible = ref(false);
const userApi = ref("");
const batchOptionsUser = () => {
  let records = tableRef.value?.$table.getCheckboxRecords();
  if (!records?.length) return ElMessage.warning("请至少选择一条数据!");
  const ids = records.map((item) => item.id);
  userData.value = {
    userData: [],
    parmas: { goods_category_ids: ids },
  };
  userApi.value = api.setgoodsBatchAccessUser;
  userVisible.value = true;
};
const handleUesrManage = async (val) => {
  const { data } = await api.getAccessUser({ goods_category_id: val.id });
  userData.value = {
    userData: data?.user_ids || [],
    parmas: { goods_category_id: val.id },
  };
  userApi.value = api.setAccessUser;
  userVisible.value = true;
};
const refresh = () => {
  tableRef?.value.$table.commitProxy("query");
};

const filterData = (data, query) => {
  return data.filter((item) => {
    const isMatch = item.name.includes(query);
    if (item.children) {
      item.children = filterData(item.children, query); // 递归处理子节点
    }
    return isMatch || (item.children && item.children.length > 0); // 匹配或有子节点
  });
};
</script>
<style lang="scss" scoped>
.vx-table {
  height: calc(100% - 40px) !important;
}
:deep(.vxe-grid--pager-wrapper) {
  display: none;
}
</style>
